package com.xj.nrpc.client.future;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.xj.nrpc.core.util.RequestEntity;
import com.xj.nrpc.core.util.ResponseEntity;

public class DefaultFuture {

	public final static ConcurrentHashMap<String, DefaultFuture> map = new ConcurrentHashMap<String, DefaultFuture>();

	final Lock lock = new ReentrantLock();
	final Condition condition = lock.newCondition();

	private ResponseEntity resp;

	public DefaultFuture(RequestEntity req) {
		map.put(req.getId(), this);
	}

	public ResponseEntity get() {
		lock.lock();
		try {
			while (!done()) {
				condition.await();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
		return this.resp;
	}

	public static void recive(ResponseEntity resp) {
		DefaultFuture def = map.get(resp.getId());
		if (def != null) {
			Lock lock = def.lock;
			lock.lock();
			try {
				def.setResp(resp);
				def.condition.signal();
				map.remove(resp.getId());
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				lock.unlock();
			}
		}
	}

	public ResponseEntity getResp() {
		return resp;
	}

	public void setResp(ResponseEntity resp) {
		this.resp = resp;
	}

	private boolean done() {
		if (this.resp != null) {
			return true;
		}
		return false;
	}

}
